﻿using RFID.BLL;
using RFID.Model;
using System;

namespace RFID.PC.AppCenter
{
    public partial class AddWorkForm : ChildForm
    {
        public AddWorkForm(MainForm main, object sender)
            : base(main, sender)
        {
            InitializeComponent();
            Text = Title;
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            if (!MainForm.ComEnable)
            {
                ShowMessage("未打开串口！", false);
                return;
            }
            if (EPCSDKHelper.SetReaderParameters(MainForm.Com, 0x70, 1, new byte[] { 2 }, 0) && EPCSDKHelper.SetReaderParameters(MainForm.Com, 0x87, 1, new byte[] { 1 }, 0) && EPCSDKHelper.SetReaderParameters(MainForm.Com, 0x7A, 1, new byte[] { 1 }, 0) && EPCSDKHelper.SetReaderParameters(MainForm.Com, 0x7B, 1, new byte[] { 2 }, 0))
            {
                EPCSDKHelper.ResumeReading(MainForm.Com, 0);
                timer1.Enabled = true;
            }
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            byte[] tagEPC = new byte[12 * 200];
            if (EPCSDKHelper.IdentifyUploadedMultiTags(MainForm.Com, out byte tagNum, tagEPC, null, null))
            {
                for (int i = 0; i < tagNum; i++)
                {
                    byte[] data = new byte[12];
                    Buffer.BlockCopy(tagEPC, 12 * i, data, 0, 12);
                    var work = new WorkInfo()
                    {
                        RId = ConvertHelper.ByteArrayToHexString(data)
                    };
                    var result = WorkInfoBLL.AddWork(work);
                    if (result.Status)
                    {
                        var message = result.Data ? "签退" : "签到";
                        listBox1.Items.Add($"{work.RId}{message}成功！");
                    }
                    else
                    {
                        listBox1.Items.Add($"{work.RId}考勤失败！{result.Message}！");
                    }
                }
            }

            listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }

        private void AddWorkForm_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (MainForm.ComEnable)
            {
                EPCSDKHelper.SetReaderParameters(MainForm.Com, 0x70, 1, new byte[] { 1 }, 0);
                EPCSDKHelper.SetReaderParameters(MainForm.Com, 0x87, 1, new byte[] { 0 }, 0);
            }
        }
    }
}
